package net.hserver.hp_client;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;

import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.navigation.NavigationView;
import com.king.app.dialog.AppDialog;
import com.king.app.dialog.AppDialogConfig;
import com.king.app.updater.AppUpdater;
import com.king.app.updater.http.OkHttpManager;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import net.hserver.hp_client.config.ConstConfig;
import net.hserver.hp_client.domian.vo.UserVo;
import net.hserver.hp_client.service.ProxyService;
import net.hserver.hp_client.service.UserService;
import net.hserver.hp_client.ui.home.HomeFragment;
import net.hserver.hp_client.util.SharedPreferencesUtil;

import java.util.List;

import static net.hserver.hp_client.config.ConstConfig.URL;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    private UserService userService = new UserService();

    private TextView head_username;

    private TextView head_ports;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        head_username = headerView.findViewById(R.id.head_username);
        head_ports = headerView.findViewById(R.id.head_ports);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        String username = SharedPreferencesUtil.getString(getApplicationContext(), ConstConfig.USERNAME, null);
        String password = SharedPreferencesUtil.getString(getApplicationContext(), ConstConfig.PASSWORD, null);

        if (username == null || password == null) {
            createLoginAlert().show();
        } else {
            //开始登录
            userService.login(username, password, handler);
        }

        if (SharedPreferencesUtil.getBoolean(getApplicationContext(), ConstConfig.ABOUT, true)) {
            createAboutAlert().show();
        }
        checkUpdate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkFloat();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkFloat(){
        if(!Settings.canDrawOverlays(this)){
            //没有悬浮窗权限,跳转申请
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
        }
    }

    private void checkUpdate() {
        userService.getVersion(new VersionHandler());
    }

    private void update(String content) {
        AppDialogConfig config = new AppDialogConfig();
        config.setTitle("HP-Client更新提示")
                .setOk("升级")
                .setContent(content)
                .setOnClickOk(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AppUpdater.Builder()
                                .serUrl(URL + "/app/download")
                                .setFilename("HP-Client" + System.currentTimeMillis() + ".apk")
                                .build(getApplicationContext())
                                .setHttpManager(OkHttpManager.getInstance())//不设置HttpManager时，默认使用HttpsURLConnection下载，如果使用OkHttpClient实现下载，需依赖okhttp库
                                .start();
                        AppDialog.INSTANCE.dismissDialogFragment(getSupportFragmentManager());
                    }
                });
        AppDialog.INSTANCE.showDialogFragment(getSupportFragmentManager(), config);
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about:
                createAboutAlert().show();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public AlertDialog createRegAlert() {
        LayoutInflater factory = LayoutInflater.from(this);
        final View view = factory.inflate(R.layout.reg, null);
        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("注册中心")
                .setView(view)
                .setPositiveButton("确定", null).setNegativeButton("取消", null).create();

        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {


                Button positionButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                Button negativeButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                positionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //处理登录
                        String txt_username = ((EditText) view.findViewById(R.id.txt_username)).getText().toString();
                        String txt_password = ((EditText) view.findViewById(R.id.txt_password)).getText().toString();
                        String txt_repassword = ((EditText) view.findViewById(R.id.txt_repassword)).getText().toString();
                        if (txt_username.trim().length() < 5) {
                            Toast.makeText(getApplicationContext(), "用户长度名必须大于5", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (txt_password.trim().length() < 5) {
                            Toast.makeText(getApplicationContext(), "密码长度必须大于5", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (!txt_repassword.equals(txt_repassword)) {
                            Toast.makeText(getApplicationContext(), "两次密码不一样", Toast.LENGTH_LONG).show();
                            return;
                        }
                        userService.reg(txt_username, txt_password, new RegHandler(alertDialog));
                    }
                });
                negativeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });


            }
        });
        return alertDialog;
    }


    public AlertDialog createLoginAlert() {
        LayoutInflater factory = LayoutInflater.from(this);
        final View view = factory.inflate(R.layout.login, null);

        String username = SharedPreferencesUtil.getString(getApplicationContext(), ConstConfig.USERNAME, null);
        String password = SharedPreferencesUtil.getString(getApplicationContext(), ConstConfig.PASSWORD, null);
        ((EditText) view.findViewById(R.id.txt_username)).setText(username);
        ((EditText) view.findViewById(R.id.txt_password)).setText(password);
        view.findViewById(R.id.txt_toregister).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createRegAlert().show();
            }
        });


        return new AlertDialog.Builder(MainActivity.this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("登录")
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //处理登录
                        String txt_username = ((EditText) view.findViewById(R.id.txt_username)).getText().toString();
                        String txt_password = ((EditText) view.findViewById(R.id.txt_password)).getText().toString();
                        SharedPreferencesUtil.putString(getApplicationContext(), ConstConfig.USERNAME, txt_username);
                        SharedPreferencesUtil.putString(getApplicationContext(), ConstConfig.PASSWORD, txt_password);
                        userService.login(txt_username, txt_password, handler);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        System.exit(0);
                    }
                })
                .create();
    }


    public AlertDialog createAboutAlert() {
        LayoutInflater factory = LayoutInflater.from(this);
        final View view = factory.inflate(R.layout.about, null);
        return new AlertDialog.Builder(MainActivity.this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("关于")
                .setView(view)
                .setNegativeButton("好的，我知道了", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        SharedPreferencesUtil.putBoolean(getApplicationContext(), ConstConfig.ABOUT, false);
                    }
                })
                .create();
    }


    @SuppressLint("HandlerLeak")
    public final Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                String s = msg.obj.toString();
                UserVo userVo = JSON.parseObject(s, UserVo.class);
                ConstConfig.USER_VO = userVo;
                head_username.setText(userVo.getUsername());
                head_ports.setText("支持端口：" + (userVo.getPorts() != null ? userVo.getPorts().toString() : "无"));
                HomeFragment.setSpData();
                Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
            } else if (msg.what == -1) {
                Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_LONG).show();
                createLoginAlert().show();
            }
            super.handleMessage(msg);
        }
    };


    class RegHandler extends Handler {

        private AlertDialog alertDialog;

        public RegHandler(AlertDialog alertDialog) {
            this.alertDialog = alertDialog;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                alertDialog.dismiss();
            } else if (msg.what == -1) {
                Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }

    class VersionHandler extends Handler {

        private String getAppVersionCode(Context context) {
            try {
                PackageManager pm = context.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
                return pi.versionName;
            } catch (Exception ignored) {
            }
            return null;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                try {
                    Object obj = msg.obj;
                    if (obj != null) {
                        JSONObject jsonObject = JSON.parseObject(obj.toString());
                        String versionCode = jsonObject.getString("versionCode");
                        if (!versionCode.trim().equals(getAppVersionCode(getApplicationContext()).trim())) {
                            update("当前版本：" + getAppVersionCode(getApplicationContext()) + "\n最新版本：" + versionCode + "\n" + jsonObject.getString("updateContent"));
                        }
                    }
                } catch (Throwable e) {
                    Toast.makeText(getApplicationContext(), "检查更新失败", Toast.LENGTH_LONG).show();
                }
            } else if (msg.what == -1) {
                Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }


}
